<script setup lang="ts">
  import { ref, watch, computed, reactive } from 'vue';
  import { useBooleanStore } from '@/store';
  import {
    ERPBoxOut,
    saveWorkbin,
    inWorkbin,
  } from '@/api/inventory-management';
  import { Notification } from '@arco-design/web-vue';

  const props = defineProps<{
    tableData: any;
  }>();
  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      key: 'PAGEHELPER_ROW_ID',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '缓存箱编号',
      dataIndex: 'workbinCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '成品型号',
      dataIndex: 'mProductNumber',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '出库数量',
      dataIndex: 'erpOutQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '条码',
      dataIndex: 'barcode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '图号',
      dataIndex: 'itemCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '质量编号/件号',
      dataIndex: 'qualityCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '交接单号',
      dataIndex: 'deliveryPlanCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '当前操作台',
      dataIndex: 'updateIp',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  const booleanStore = useBooleanStore();
  // 创建一个响应式的本地副本
  const localTableData = ref<any>();
  // 数据库一共有多少条
  const total = ref<number>(1);
  const pageNum = ref<number>(1);
  const pageSize = ref<number>(10);
  const selectedKeys = ref<string[]>([]);
  // 计算已选择的表格数据
  const selectedTableData = computed(() => {
    return localTableData.value.filter((item: any) =>
      selectedKeys.value?.includes(item.PAGEHELPER_ROW_ID)
    );
  });
  const rowSelection = reactive({
    type: 'checkbox' as 'checkbox' | 'radio',
    showCheckedAll: true,
  });
  // 监听props.tableData的变化，并更新本地副本
  watch(
    () => props.tableData,
    () => {
      localTableData.value = props.tableData?.retData;
      total.value = props.tableData?.totalCount || 0;
    },
    { immediate: true }
  );
  // 监听页面变化
  watch([pageNum, pageSize], () => {
    booleanStore.setPage(pageNum.value, pageSize.value, 34);
  });
  // 监听已选择数据的序号，并更新到已选择表格数据行字段
  function change(e: any) {
    pageNum.value = e;
  }
  function changeSize(e: any) {
    pageSize.value = e;
  }

  // 缓存箱出库
  async function boxOut() {
    if (selectedKeys.value?.length === 0) {
      Notification.warning({
        title: '提示',
        content: '请至少选择一条数据',
        closable: true,
      });
      return;
    }
    const response = await ERPBoxOut({
      data: selectedTableData.value[0],
      datas: selectedTableData.value,
    });
    if (response.retCode) {
      if (response.retCode === '200') {
        Notification.success({
          title: '成功',
          content: '缓存箱出库成功',
          closable: true,
        });
        selectedKeys.value = [];
        booleanStore.watchUpdate(16);
      } else {
        Notification.error({
          title: '错误',
          content: '缓存箱出库失败',
          closable: true,
        });
      }
    } else {
      Notification.error({
        title: '提示',
        content: '获取数据失败，请联系管理员',
        closable: true,
      });
    }
  }
  // 保存
  async function saveBox() {
    if (selectedKeys.value?.length === 0) {
      Notification.warning({
        title: '提示',
        content: '请至少选择一条数据',
        closable: true,
      });
      return;
    }
    const response = await saveWorkbin({
      data: selectedTableData.value,
    });
    if (response.retCode) {
      if (response.retCode === '200') {
        Notification.success({
          title: '成功',
          content: response.retMsg,
          closable: true,
        });
        selectedKeys.value = [];
        booleanStore.watchUpdate(16);
      } else {
        Notification.error({
          title: '失败',
          content: response.retMsg,
          closable: true,
        });
      }
    } else {
      Notification.error({
        title: '失败',
        content: '获取数据失败，请联系管理员',
        closable: true,
      });
    }
  }
  // 缓存箱回库
  async function boxIn() {
    if (selectedKeys.value?.length !== 1) {
      Notification.warning({
        title: '提示',
        content: '请至少选择一条数据',
        closable: true,
      });
      return;
    }
    booleanStore.toggleBool(0);
    try {
      const response = await inWorkbin({
        data: selectedTableData.value[0].workbinCode,
      });
      if (response.retCode) {
        if (response.retCode === '200') {
          booleanStore.toggleBool(0);
          Notification.success({
            title: '成功',
            content: response.retMsg,
            closable: true,
          });
          selectedKeys.value = [];
          booleanStore.watchUpdate(16);
        } else {
          booleanStore.toggleBool(0);
          Notification.error({
            title: '失败',
            content: response.retMsg,
            closable: true,
          });
          selectedKeys.value = [];
          booleanStore.watchUpdate(16);
        }
      } else {
        Notification.error({
          title: '失败',
          content: '获取数据失败，请联系管理员',
          closable: true,
        });
      }
    } catch (error) {
      booleanStore.toggleBool(0);
      Notification.error({
        title: '失败',
        content: '数据发送超时',
        closable: true,
      });
    } finally {
      booleanStore.toggleBool(0);
    }
  }
</script>

<template>
  <a-space>
    <a-button type="primary" size="large" @click="boxOut">缓存箱出库 </a-button>
    <a-button type="primary" size="large" @click="saveBox">保存 </a-button>
    <a-button type="primary" size="large" @click="boxIn">缓存箱回库</a-button>
  </a-space>
  <div style="margin-top: 8px">
    <a-table
      v-model:selected-keys="selectedKeys"
      :stripe="true"
      class="top-table"
      :pagination="false"
      :columns="columns"
      :data="localTableData"
      row-key="PAGEHELPER_ROW_ID"
      :row-selection="rowSelection"
    >
    </a-table>
    <div class="page-position">
      <a-pagination
        :total="total"
        :current="pageNum"
        :page-size="pageSize"
        show-total
        show-jumper
        show-page-size
        @change="change"
        @update:page-size="changeSize"
      />
    </div>
  </div>
</template>

<style scoped>
  .top-table {
    white-space: nowrap;
  }
  .page-position {
    margin-top: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
